/**
 * 增强的WebSocket连接器 - 基于Linus设计哲学
"简单胜过复杂，但要处理真实场景"
 */

class EnhancedWebSocket {
    constructor(url, options = {}) {
        this.url = url;
        this.options = {
            reconnectInterval: 5000,
            maxReconnectAttempts: 10,
            timeout: 8000,
            ...options
        };
        
        this.reconnectAttempts = 0;
        this.isManualClose = false;
        this.connect();
    }
    
    connect() {
        try {
            this.ws = new WebSocket(this.url);
            this.setupEventHandlers();
        } catch (error) {
            console.error('WebSocket连接失败:', error);
            this.scheduleReconnect();
        }
    }
    
    setupEventHandlers() {
        this.ws.onopen = () => {
            console.log('WebSocket连接已建立');
            this.reconnectAttempts = 0;
            if (this.options.onOpen) {
                this.options.onOpen();
            }
        };
        
        this.ws.onmessage = (event) => {
            if (this.options.onMessage) {
                this.options.onMessage(event);
            }
        };
        
        this.ws.onerror = (error) => {
            console.error('WebSocket错误:', error);
            if (this.options.onError) {
                this.options.onError(error);
            }
        };
        
        this.ws.onclose = () => {
            console.log('WebSocket连接已关闭');
            if (this.options.onClose) {
                this.options.onClose();
            }
            
            if (!this.isManualClose) {
                this.scheduleReconnect();
            }
        };
    }
    
    scheduleReconnect() {
        if (this.reconnectAttempts >= this.options.maxReconnectAttempts) {
            console.error('达到最大重连次数，停止重连');
            return;
        }
        
        this.reconnectAttempts++;
        console.log(`${this.options.reconnectInterval/1000}秒后尝试第${this.reconnectAttempts}次重连...`);
        
        setTimeout(() => {
            this.connect();
        }, this.options.reconnectInterval);
    }
    
    send(data) {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(data);
        } else {
            console.warn('WebSocket未连接，无法发送消息');
        }
    }
    
    close() {
        this.isManualClose = true;
        if (this.ws) {
            this.ws.close();
        }
    }
    
    getReadyState() {
        return this.ws ? this.ws.readyState : WebSocket.CLOSED;
    }
    
    isConnected() {
        return this.getReadyState() === WebSocket.OPEN;
    }
}

// 导出为全局函数以兼容现有代码
window.createEnhancedWebSocket = function(url, options) {
    return new EnhancedWebSocket(url, options);
};